<template>
    <div class="content-main">
        <div class="breadcrumb">
            <div class="breadcrumb-icon">
                <img src="./../../assets/images/breadcrumb_icon.png" />
            </div>
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>教师管理</el-breadcrumb-item>
            </el-breadcrumb>
            <!-- <bread-crumb-back></bread-crumb-back> -->
        </div>
        <div class="content-box">
            <div class="search-box">
                <div class="search-item">
                    <span class="search-title">教师姓名: </span>
                    <el-input v-model="teacherName" placeholder="请输入教师姓名" style="float:left; width:auto;"></el-input>
                </div>
                <div class="search-item">
                    <el-button type="primary" @click="searchFn">搜索</el-button>
                </div>
                <div class="search-item" style="float:right; margin:0;">
                    <a href="/dataplatform/system/manager/downloadAddUserFile?type=2" style="margin-right:10px;"><el-button type="primary">模板下载</el-button></a>
                    <el-button type="primary" @click="importTeacher">导入教师</el-button>
                    <el-button type="primary" @click="addTeacher">添加教师</el-button>
                    <el-button type="primary" @click="deleteList">批量删除</el-button>
                </div>
            </div>
            <div class="table-content" v-loading="tableLoading">
                <el-table
                :data="tableData"
                ref="multipleTable"
                border
                style="width: 100%"
                @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="100px;">
                    </el-table-column>
                    <el-table-column prop="userName" label="姓名">
                    </el-table-column>
                    <el-table-column  label="性别">
                        <template slot-scope="scope">
                            <span>{{scope.row.userSex == 'm' ? '男' : '女'}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="userNumber" label="工号">
                    </el-table-column>
                    <el-table-column prop="telephone" label="联系方式">
                        <template slot-scope="scope">
                            <span>{{ scope.row.telephone }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button type="text" size="small" @click="modifyInfo(scope.row.id,scope.row.userName,scope.row.userSex,scope.row.telephone,scope.row.userNumber,scope.row.password)">修改</el-button>
                            <el-button type="text" size="small" @click="initPassword(scope.row.id)">初始化密码</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-size="pagesize"
                    layout="total, prev, pager, next, jumper"
                    :total="totalCount"
                    style="margin-top: 20px; text-align: center;">
                </el-pagination>
            </div>
            <el-dialog title="添加教师" :visible.sync="dialogFormVisible" width="500px" @close="closeDialog">
                <el-form ref="form" :model="form" :rules="rules"  label-width="100px">
                    <el-form-item label="姓名 :" prop="teacherName">
                        <el-input type="text" v-model="form.teacherName" style="width: 50%;"></el-input>
                    </el-form-item>
                    <el-form-item label="性别 :">
                        <el-radio-group v-model="form.gender">
                            <el-radio :label="1">男</el-radio>
                            <el-radio :label="2">女</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="联系方式 :" style="width:80%;">
                        <el-input  v-model="form.contactWay"></el-input>
                    </el-form-item>
                    <el-form-item label="工号 :" prop="jobNumber" style="width:80%;">
                        <el-input type="text" v-model="form.jobNumber"></el-input>
                    </el-form-item>
                    <el-form-item label="密码 :" prop="passWord" style="width:80%;">
                        <el-input type="password" v-model="form.passWord" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="确认密码 :"  prop="checkPass" style="width:80%;">
                        <el-input type="password" v-model="form.checkPass" auto-complete="off"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer" style="text-align:center;">
                    <el-button type="primary" @click="submitForm('form')">保存</el-button>
                </div>
            </el-dialog>
            <el-dialog class="common-tool-dialog" title="导入教师" :visible.sync="dialogFormVisible2" width="500px" @close="closeTeacher" @clsoe="closeTeacherDialog">
                <el-form :model="form2" :rules="rules2" ref="form2">
                    <el-form-item prop="versionFile" class="version-file">
                        <el-button type="primary">上传文件<input id="version-file-input" type="file" multiple="multiple" auto-complete="off" @change="getFile"></input></el-button>
                        <p v-if="form2.versionFile.length>0">已选: {{form2.versionFile}}</p>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer" style="text-align:center;">
                    <el-button @click="closeTeacher">取消</el-button>
                    <el-button type="primary" @click="saveForm('form2')">确认</el-button>
                </div>
            </el-dialog>
            <el-dialog title="修改教师" :visible.sync="dialogFormVisible3" width="500px" @close="closeModifyDialog">
                <el-form ref="form3" :model="form3" :rules="rules3"  label-width="110px">
                    <el-form-item label="姓名 :" prop="teacherName">
                        <el-input type="text" v-model="form3.teacherName" style="width: 50%;"></el-input>
                    </el-form-item>
                    <el-form-item label="性别 :">
                        <el-radio-group v-model="form3.gender">
                            <el-radio :label="1">男</el-radio>
                            <el-radio :label="2">女</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="联系方式 :" style="width:80%;">
                        <el-input  v-model="form3.contactWay"></el-input>
                    </el-form-item>
                    <el-form-item label="工号 :" style="width:80%;">
                        <el-input type="text" disabled v-model="form3.jobNumber"></el-input>
                    </el-form-item>
                    <!-- <el-form-item label="是否修改密码 :" style="width:80%;">
                        <el-radio-group v-model="form3.isModify">
                            <el-radio :label="1">是</el-radio>
                            <el-radio :label="2">否</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item v-if="form3.isModify == 1" label="密码 :" prop="passWord" style="width:80%;">
                        <el-input type="password" v-model="form3.passWord" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item v-if="form3.isModify == 1" label="确认密码 :"  prop="checkPass" style="width:80%;">
                        <el-input type="password" v-model="form3.checkPass" auto-complete="off"></el-input>
                    </el-form-item> -->
                </el-form>
                <div slot="footer" class="dialog-footer" style="text-align:center;">
                    <el-button type="primary" @click="submitForm3('form3')">保存</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>
    import BreadCrumbBack from '@/components/breadCrumbBack.vue'
    import {isvalidPhone} from './../../api/validate.js'
    export default {
        components: {
            BreadCrumbBack
        },
        data () {
            //手机号验证
            var validPhone = (rule, value,callback)=>{
                if (!value){
                    callback(new Error('请输入电话号码'))
                }else  if (!isvalidPhone(value)){
                    callback(new Error('请输入正确的11位手机号码'))
                }else {
                    callback()
                }
            }
            var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'))
                } else {
                    if (this.form.checkPass !== '') {
                        this.$refs.form.validateField('checkPass')
                    }
                        callback()
                    }
                }
			var validatePass2 = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('请再次输入密码'))
				} else if (value !== this.form.passWord) {
					callback(new Error('两次输入密码不一致!'))
				} else {
					callback()
				}
            }
            var validatePass3 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'))
                } else {
                    if (this.form3.checkPass !== '') {
                        this.$refs.form3.validateField('checkPass')
                    }
                        callback()
                    }
                }
			var validatePass4 = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('请再次输入密码'))
				} else if (value !== this.form3.passWord) {
					callback(new Error('两次输入密码不一致!'))
				} else {
					callback()
				}
            }
            return {
                teacherName: '',
                tableLoading: false,
                tableData: [],
                currentPage:1,
                pagesize:10,
                totalCount: 1000,
                multipleSelection: [],
                dialogFormVisible: false,
                form: {
                    teacherName: '',
                    gender: 1,
                    contactWay: '',
                    jobNumber: '',
                    passWord: '',
                    checkPass: ''
                },
                //表单验证
				rules: {
                    teacherName: [
                        { required: true, message: '请输入姓名', trigger: 'blur' }
                    ],
                    contactWay: [
                        { required: true, validator: validPhone, trigger: 'blur' }
                    ],
                    jobNumber: [
                        { required: true, message: '请输入工号', trigger: 'blur' }
                    ],
                    passWord: [
                        { required: true, message: '请输入新密码', trigger: 'blur' },
						{ required: true, validator: validatePass, trigger: 'blur' }
					],
					checkPass: [
                        { required: true, message: '请确认密码', trigger: 'blur' },
						{ required: true, validator: validatePass2, trigger: 'blur' }
                    ]
                },
                dialogFormVisible2: false,
                form2: {
                    fileName: '',
                    versionFile: ''
                },
                rules2: {
                    versionFile: [
                        { required: true, message: '请上传文件', trigger: 'blur' }
					]
                },
                dialogFormVisible3: false,
                form3: {
                    teacherName: '',
                    gender: 1,
                    contactWay: '',
                    jobNumber: '',
                    isModify: 2,
                    passWord: '',
                    checkPass: ''
                },
                //表单验证
				rules3: {
                    teacherName: [
                        { required: true, message: '请输入姓名', trigger: 'blur' }
                    ],
                    contactWay: [
                        { required: true, validator: validPhone, trigger: 'blur' }
                    ],
                    jobNumber: [
                        { required: true, message: '请输入工号', trigger: 'blur' }
                    ],
                    passWord: [
                        { required: true, message: '请输入新密码', trigger: 'blur' },
						{ required: true, validator: validatePass3, trigger: 'blur' }
					],
					checkPass: [
                        { required: true, message: '请确认密码', trigger: 'blur' },
						{ required: true, validator: validatePass4, trigger: 'blur' }
                    ]
                },
                teacherId: ''
            }
        },
        created () {
            this.init() //初始化
        },
        methods: {
            init() {
                let self = this
                self.$http.get('/dataplatform/system/manager/teacherList?pageNum='+self.currentPage +'&pageSize='+self.pagesize + '&userName='+self.teacherName).then((response) => {
                    let res = response.data
                    if(res.code == '200') {
                        self.tableData = res.data.list
                        self.totalCount = res.data.total
                    }else if(res.code == '401'){
                        self.$router.replace({
                            path:'/login'
                        })
                    }else{
                        self.$message.error(res.message)
                    }
                })
            },
            //表格分页
			handleSizeChange: function (size) {
				this.pagesize = size;
			},
			handleCurrentChange: function(currentPage) {
                this.currentPage = currentPage
                this.init()
            },
            //全选
			handleSelectionChange(val) {
				let valArr = []
				for(let i = 0; i < val.length; i++){
					valArr.push(val[i].id)
				}
				this.multipleSelection = valArr
            },
            //修改
            modifyInfo(id,userName,userSex,telephone,userNumber,password) {
                this.teacherId = id
                this.form3.teacherName = userName
                this.form3.gender = userSex == 'm' ? 1 : 2
                this.form3.contactWay = telephone
                this.form3.jobNumber = userNumber
                this.form3.passWord = ''
                this.form3.checkPass = ''
                this.dialogFormVisible3 = true
            },
            //修改弹窗关闭
            closeModifyDialog(){
                this.$refs.form3.resetFields()
            },
            //导入教师
            importTeacher(){
                this.form2.fileName = ''
                this.form2.versionFile = ''
                this.dialogFormVisible2 = true
            },
            //关闭导入教师弹窗
            closeTeacherDialog(){
                this.$refs.form2.resetFields()
            },
            //添加教师
            addTeacher() {
                this.form.teacherName = ''
                this.form.gender = 1
                this.form.contactWay = ''
                this.form.jobNumber = ''
                this.form.passWord = ''
                this.form.checkPass = ''
                this.dialogFormVisible = true
            },
            //关闭弹窗
            closeDialog(){
                this.$refs.form.resetFields()
            },
            //添加教师表单提交
            submitForm(formName) {
                let self = this
				self.$refs[formName].validate((valid) => {
                    if (valid) {
                        self.$http.post('/dataplatform/system/manager/addTeacher',{
                            userName: self.form.teacherName,
                            userSex: self.form.gender == 1 ? 'm' : 'f',
                            telephone: self.form.contactWay,
                            userNumber: self.form.jobNumber,
                            password: self.form.passWord
                        }).then((response) => {
                            let res = response.data
                            if(res.code == '200') {
                                self.$message({
                                    message: '添加成功',
                                    type: 'success'
                                })
                                self.init()
                                self.dialogFormVisible = false
                                self.$refs[formName].resetFields()
                            }else if(res.code == '401'){
                                self.$router.replace({
                                    path:'/login'
                                })
                            }else{
                                self.$message.error(res.message)
                            }
                        })
                    }
                })
            },
            //删除选中
			deleteList() {
				let self = this;
				if(self.multipleSelection.length == 0){
                    self.$message({
                        message: '请选择要删除的信息',
                        type: 'warning'
                    })
					return
				}
				self.$confirm('是否删除选中?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					self.$http.post('/dataplatform/system/manager/delUser',{
                        delType: 3,
                        idList: self.multipleSelection
                    }).then((response) => {
						let res = response.data;
						if(res.code == '200'){
                            self.$message({
                                message: '删除成功',
                                type: 'success'
                            })
                            self.currentPage = 1
							self.init()
						}else if(res.code == '401'){
                            self.$router.replace({
                                path:'/login'
                            })
                        }else{
                            self.$message.error(res.message)
                        }
					},(err) => {
						console.log('err');
					})
				}).catch(() => {
				});
            },
            //搜索
            searchFn() {
                let self = this
                self.currentPage = 1
                self.pagesize = 10
                self.init()
            },
            //上传文件
            getFile($event) {
                let fileType = $event.target.files[0].name
                    fileType = fileType.substring((fileType.lastIndexOf('.') + 1), fileType.length)
                if(fileType != 'xls' && fileType != ".xlsx"){
                    this.$message.error('请上传xls格式的Excel文件!')
                    return
                }
                this.form2.fileName = $event.target.files[0]
                this.form2.versionFile = $event.target.files[0].name
            },
            //关闭弹窗
            closeTeacher(){
                this.dialogFormVisible2 = false
                $('#version-file-input').val('')
            },
            //导入教师表单提交
            saveForm(form2) {
                let self = this

                let formData = new FormData()
                    formData.append('file', self.form2.fileName);
                    formData.append('addType', 2);
				self.$refs[form2].validate((valid) => {
                    if (valid) {
                        const loading = this.$loading({
                            lock: true,
                            text: '文件导入中',
                            spinner: 'el-icon-loading',
                            background: 'rgba(0, 0, 0, 0.7)'
                        })
                        self.$http.post('/dataplatform/system/manager/importUser', formData, {headers: {'Content-Type': 'multipart/form-data'}}).then((response) => {
                            let res = response.data
                            if(res.code == '200') {
                                self.$message({
                                    message: '上传成功',
                                    type: 'success'
                                })
                                loading.close()
                                self.init()
                                $('#version-file-input').val('')
                                self.dialogFormVisible2 = false
                                self.$refs[form2].resetFields()
                            }else if(res.code == '401'){
                                loading.close()
                                self.$router.replace({
                                    path:'/login'
                                })
                            }else{
                                loading.close()
                                self.$message.error(res.message)
                            }
                        })
                    }
                })
            },
            //初始化密码
            initPassword(id){
                let self = this
                self.$http.post('/dataplatform/system/mana/a/initializePassword',{
                    id: id
                }).then((response) => {
                    let res = response.data
                    if(res.code == '200') {
                        self.$message({
                            message: '初始化成功',
                            type: 'success'
                        })
                        self.init()
                    }else if(res.code == '401'){
                        self.$router.replace({
                            path:'/login'
                        })
                    }else{
                        self.$message.error(res.message)
                    }
                })
            },
            //修改教师表单提交
            submitForm3(formName) {
                let self = this
				self.$refs[formName].validate((valid) => {
                    if (valid) {
                        // let data = {}
                        // if(self.form3.isModify == 1){
                        //     data = {
                        //         id: self.teacherId,
                        //         userName: self.form3.teacherName,
                        //         userSex: self.form3.gender == 1 ? 'm' : 'f',
                        //         telephone: self.form3.contactWay,
                        //         savePwdMark: self.form3.isModify,
                        //         password: self.form3.passWord
                        //     }
                        // }else if(self.form3.isModify == 2){
                        //     data = {
                        //         id: self.teacherId,
                        //         userName: self.form3.teacherName,
                        //         userSex: self.form3.gender == 1 ? 'm' : 'f',
                        //         telephone: self.form3.contactWay,
                        //         savePwdMark: self.form3.isModify
                        //     }
                        // }
                        self.$http.post('/dataplatform/system/manager/saveTeacher',{
                            id: self.teacherId,
                            userName: self.form3.teacherName,
                            userSex: self.form3.gender == 1 ? 'm' : 'f',
                            telephone: self.form3.contactWay,
                            savePwdMark: 2,
                            password: self.form3.passWord
                        }).then((response) => {
                            let res = response.data
                            if(res.code == '200') {
                                self.$message({
                                    message: '修改成功',
                                    type: 'success'
                                })
                                self.init()
                                self.dialogFormVisible3 = false
                                self.$refs[formName].resetFields()
                            }else if(res.code == '401'){
                                self.$router.replace({
                                    path:'/login'
                                })
                            }else{
                                self.$message.error(res.message)
                            }
                        })
                    }
                })
            }
        }
    }
</script>
